package com.waitingresult.thread.cacheline;

/**
 * All right reserved,Designed By WangShuai
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : CacheLineDemo
 * @Description :  理解CPU缓存行的概念， CPU读取一行数据 是64个字节。 而一个Long类型占8个字节。提升效率
 * @date : 2022/9/18 14:27
 */
public class CacheLineDemo {
    private static class Parent{
       private volatile  long p1,p2,p3,p4,p5,p6,p7;
    }
    private static class T extends Parent{
        private volatile long x = 0L ;
    }
    //创建一个T类型的数组， 长度为2

    public static T[] arr = new T[2];
    static {
        arr[0] = new T();
        arr[1] = new T();
    }
    public static void main(String[] args) throws Exception {
        Thread thread1 = new Thread(()->setArrayIndexValue(0));
        Thread thread2 = new Thread(()->setArrayIndexValue(1));
        long start = System.nanoTime();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.err.println((start-System.nanoTime())/ 100_000L);
    }

    private static void setArrayIndexValue(int index) {
        for (long i = 0; i < 1000_0000L; i++) {
            arr[index].x = i;
        }
    }
}
